<script setup lang="ts">
import { ref, nextTick, onMounted } from "vue";
import { registerMap, getMap } from "echarts/core";
import { optionHandle, regionCodes } from "./center.map";
import BorderBox13 from "@/components/datav/border-box-13/border-box-13.vue";
import VChart from "@/components/v-chart/v-chart.vue";
import type { MapdataType } from "./center.map";

const props = withDefaults(
  defineProps<{
    title: number | string;
  }>(),
  {
    title: "地图",
  }
);

const option = ref({});
const code = ref("china"); //china 代表中国 其他地市是行政编码

const dataSetHandle = async (regionCode: string, list: object[]) => {
  const geojson: any = await getGeojson(regionCode);
  let cityCenter: any = {};
  let mapData: MapdataType[] = [];
  
  //获取当前地图每块行政区中心点
  geojson.features.forEach((element: any) => {
    cityCenter[element.properties.name] = element.properties.centroid || element.properties.center;
  });
  
  //当前中心点如果有此条数据中心点则赋值x，y
  list.forEach((item: any) => {
    if (cityCenter[item.name]) {
      mapData.push({
        name: item.name,
        value: cityCenter[item.name].concat(item.value),
      });
    }
  });
  
  await nextTick();
  option.value = optionHandle(regionCode, list, mapData);
};

const getData = async (regionCode: string) => {
  // 模拟数据
  const mockData = {
    success: true,
    data: {
      regionCode: regionCode,
      dataList: [
        { name: "北京市", value: 156 },
        { name: "上海市", value: 132 },
        { name: "广东省", value: 198 },
        { name: "浙江省", value: 87 },
        { name: "江苏省", value: 145 },
        { name: "山东省", value: 112 },
        { name: "河南省", value: 78 },
        { name: "四川省", value: 95 },
        { name: "湖北省", value: 68 },
        { name: "湖南省", value: 89 },
        { name: "福建省", value: 56 },
        { name: "安徽省", value: 73 },
        { name: "河北省", value: 92 },
        { name: "辽宁省", value: 61 },
        { name: "山西省", value: 45 },
        { name: "陕西省", value: 52 },
        { name: "江西省", value: 48 },
        { name: "重庆市", value: 67 },
        { name: "云南省", value: 43 },
        { name: "贵州省", value: 38 },
      ],
    },
  };

  if (mockData.success) {
    dataSetHandle(mockData.data.regionCode, mockData.data.dataList);
  }
};

const getGeojson = (regionCode: string) => {
  return new Promise<any>(async (resolve) => {
    console.log('🌍 获取GeoJSON，regionCode:', regionCode);
    let mapjson = getMap(regionCode);
    if (mapjson) {
      console.log('✅ 从缓存获取地图数据');
      mapjson = mapjson.geoJSON;
      resolve(mapjson);
    } else {
      // 加载 GeoJSON 文件
      // H5 端需要考虑 router base 路径
      const tryPaths = [
        `/secure-admin/static/map-geojson/${regionCode}.json`,  // 带 base 的绝对路径
        `./static/map-geojson/${regionCode}.json`,               // 相对路径
        `/static/map-geojson/${regionCode}.json`,                // 根路径
      ];
      
      for (const url of tryPaths) {
        try {
          console.log('📡 尝试加载地图JSON:', url);
          const response = await fetch(url);
          console.log('📡 fetch响应:', response.status, response.statusText);
          
          if (response.ok) {
            mapjson = await response.json();
            console.log('✅ 地图JSON加载成功，features数量:', mapjson?.features?.length);
            code.value = regionCode;
            registerMap(regionCode, {
              geoJSON: mapjson as any,
              specialAreas: {},
            });
            console.log('✅ 地图注册成功');
            resolve(mapjson);
            return;
          }
        } catch (error) {
          console.log(`❌ 路径 ${url} 加载失败:`, error.message);
          continue;
        }
      }
      
      console.error("❌ 所有路径都加载失败");
      resolve(null);
    }
  });
};


const mapClick = (params: any) => {
  let xzqData = regionCodes[params.name];
  if (xzqData) {
    getData(xzqData.adcode);
  } else {
    uni.showToast({
      title: '暂无下级地市',
      icon: 'none',
      duration: 2000
    });
  }
};

onMounted(() => {
  getData(code.value);
});
</script>

<template>
  <view class="centermap">
    <view class="maptitle">
      <view class="zuo"></view>
      <text class="titletext">{{ title }}</text>
      <view class="you"></view>
    </view>
    <view class="mapwrap">
      <BorderBox13>
        <view class="quanguo" @click="getData('china')" v-if="code !== 'china'">中国</view>
        <v-chart
          class="chart"
          :option="option"
          @click="mapClick"
          v-if="JSON.stringify(option) != '{}'"
        />
      </BorderBox13>
    </view>
  </view>
</template>

<style scoped lang="scss">
.centermap {
  margin-bottom: 30px;

  .maptitle {
    height: 60px;
    display: flex;
    justify-content: center;
    padding-top: 10px;
    box-sizing: border-box;

    .titletext {
      font-size: 28px;
      font-weight: 900;
      letter-spacing: 6px;
      background: linear-gradient(92deg, #0072ff 0%, #00eaff 48.8525390625%, #01aaff 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      color: transparent;
      margin: 0 10px;
    }

    .zuo,
    .you {
      background-size: 100% 100%;
      width: 29px;
      height: 20px;
      margin-top: 8px;
    }

    .zuo {
      background: url('/static/img/xiezuo.png') no-repeat;
      background-size: contain;
    }

    .you {
      background: url('/static/img/xieyou.png') no-repeat;
      background-size: contain;
    }
  }

  .mapwrap {
    height: 580px;
    width: 100%;
    box-sizing: border-box;
    position: relative;

    .quanguo {
      position: absolute;
      right: 20px;
      top: -46px;
      width: 80px;
      height: 28px;
      border: 1px solid #00eded;
      border-radius: 10px;
      color: #00f7f6;
      text-align: center;
      line-height: 26px;
      letter-spacing: 6px;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5), 0 0 6px rgba(0, 237, 237, 0.4);
      z-index: 10;
    }
  }
}

.chart {
  width: 100%;
  height: 100%;
}
</style>
